package com.ruoyi.system.frontierCommand.service.impl;

import ch.qos.logback.core.util.LocationUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.LocationUtils;
import com.ruoyi.system.basicInformation.bo.TTerminalTrajectoryQueryBo;
import com.ruoyi.system.basicInformation.service.ITTerminalTrajectoryService;
import com.ruoyi.system.basicInformation.vo.TTerminalTrajectoryVo;
import com.ruoyi.system.frontierCommand.bo.TPatrolRecordAddBo;
import com.ruoyi.system.frontierCommand.bo.TPatrolRecordEditBo;
import com.ruoyi.system.frontierCommand.domain.TPatrolMission;
import com.ruoyi.system.frontierCommand.mapper.TPatrolMissionMapper;
import com.ruoyi.system.frontierCommand.service.ITPatrolMissionService;
import com.ruoyi.system.frontierCommand.vo.TPatrolMissionVo;
import com.ruoyi.system.mobile.domain.PatrolRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.ruoyi.system.frontierCommand.bo.TPatrolRecordQueryBo;
import com.ruoyi.system.frontierCommand.domain.TPatrolRecord;
import com.ruoyi.system.frontierCommand.mapper.TPatrolRecordMapper;
import com.ruoyi.system.frontierCommand.vo.TPatrolRecordVo;
import com.ruoyi.system.frontierCommand.service.ITPatrolRecordService;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 巡护记录Service业务层处理
 *
 * @author ruoyi
 * @date 2021-05-20
 */
@Service
public class TPatrolRecordServiceImpl extends ServiceImpl<TPatrolRecordMapper, TPatrolRecord> implements ITPatrolRecordService {

    private TPatrolRecordMapper tPatrolRecordMapper;

    @Autowired
    private ITTerminalTrajectoryService iTTerminalTrajectoryService;

    /**
     * 巡护任务
    * */
    @Autowired
    private TPatrolMissionMapper tPatrolMissionMapper;

    @Override
    public TPatrolRecordVo queryById(Long id) {
        TPatrolRecord db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, TPatrolRecordVo.class);
    }

    @Override
    public List<TPatrolRecordVo> queryList(TPatrolRecordQueryBo bo) {
//        LambdaQueryWrapper<TPatrolRecord> lqw = Wrappers.lambdaQuery();
//        lqw.eq(bo.getBeginTime() != null, TPatrolRecord::getBeginTime, bo.getBeginTime());
//        lqw.eq(bo.getEndTime() != null, TPatrolRecord::getEndTime, bo.getEndTime());

        return this.baseMapper.selectDTO(bo);
        //return entity2Vo(this.list(lqw));
    }

    @Override
    public List<TPatrolRecordVo> queryRecordlistById(TPatrolRecordQueryBo bo) {
                LambdaQueryWrapper<TPatrolRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMissionId() != null, TPatrolRecord::getMissionId, bo.getMissionId());
        return entity2Vo(this.list(lqw));
    }


    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TPatrolRecordVo> entity2Vo(Collection<TPatrolRecord> collection) {
        List<TPatrolRecordVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TPatrolRecordVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<TPatrolRecord> page = (Page<TPatrolRecord>) collection;
            Page<TPatrolRecordVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(TPatrolRecordAddBo bo) {
        TPatrolRecord add = BeanUtil.toBean(bo, TPatrolRecord.class);
        validEntityBeforeSave(add, 1);
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(TPatrolRecordEditBo bo) {
        TPatrolRecord update = BeanUtil.toBean(bo, TPatrolRecord.class);
        validEntityBeforeSave(update, 2);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     * @param type   操作类型
     */
    private void validEntityBeforeSave(TPatrolRecord entity, int type) {
        TPatrolMissionVo tPatrolMission = this.tPatrolMissionMapper.selectMissionIsDeById(entity.getMissionId());
        if(tPatrolMission==null){
            //TODO 做一些数据校验,如唯一约束
            QueryWrapper<TPatrolRecord> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(TPatrolRecord::getAppUserId, entity.getAppUserId());
//            queryWrapper.lambda().eq(TPatrolRecord::getMissionId, entity.getMissionId());
            queryWrapper.lambda().orderByDesc(TPatrolRecord::getCreateTime);
            queryWrapper.last("limit 0,1");
            TPatrolRecord patrolRecord = this.baseMapper.selectOne(queryWrapper);
            if (type == 1) {
                if (patrolRecord != null && patrolRecord.getEndTime() == null) {
                    throw new BaseException("您还有未结束的巡护记录,请先结束再开始！");
                }
            } else {
                if (patrolRecord != null) {
                    entity.setId(patrolRecord.getId());
                    TTerminalTrajectoryQueryBo queryBo = new TTerminalTrajectoryQueryBo();
                    queryBo.setBeginDate(patrolRecord.getBeginTime());
                    queryBo.setOverDate(entity.getEndTime());
                    queryBo.setTerminalId(entity.getTerminalId());
                    queryBo.setTerminalType("1");
                    List<TTerminalTrajectoryVo> tTerminalTrajectoryVos = iTTerminalTrajectoryService.queryList(queryBo);
                    if (tTerminalTrajectoryVos != null && tTerminalTrajectoryVos.size()>1) {
                        double mileage = 0f;
                        for (Integer i = 0, j = 1; i < tTerminalTrajectoryVos.size(); i++, j++) {
                            if(j<tTerminalTrajectoryVos.size()-1){
                                mileage += LocationUtils.getDistance(
                                        tTerminalTrajectoryVos.get(i).getX().doubleValue(),
                                        tTerminalTrajectoryVos.get(i).getY().doubleValue(),
                                        tTerminalTrajectoryVos.get(j).getX().doubleValue(),
                                        tTerminalTrajectoryVos.get(j).getY().doubleValue()
                                );
                            }
                        }
                        entity.setDistance(mileage);
                    }
                }
            }
        }else{
            throw new BaseException("该巡护任务已删除,不能进行操作！");
        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }
}
